<template>
  <view class="whe_maxv xd">
    <view v-if="false"  class="sy_bg" style="height: 200px">
      <view style="height: 100px;">
        <image src="https://xdjzapi.towngo.cn/uploads/images/wx/202507/03/xcx_1751509412_sII69uDnZT.png"
               style="width:100%;height:120px" />
      </view>
    </view>
    <!--    一级菜单-->
    <view v-if="false" class="wh_f xyy" style="background-color: #f4f4f4">
      <view class="ddisp pad_10_0 flex_1 bhh ccgl wz_jz">
        <view class="mag_t-10"
              v-for="(item,index) in classShopList" :key="index"
              @click="addTopShop(item)"
              style="width: 20%;display: inline-block">
          <view>
            <view>
              <image :src="item.image" style="width: 60px;height: 60px" />
            </view>
            <view class="fz_12">
              {{ item.name }}
            </view>
          </view>
        </view>
      </view>
      <view class="ba_white czjz_flex wz_jz" style="width: 40px">
        <view class="wh_max">
          <view>全</view>
          <view>部</view>
          <view class="mag_t-5">
            <img src="../../static/icon/quanbu.png"
            style="width: 12px;height: 12px"/></view>
        </view>
      </view>
    </view>
    <!--    一级菜单-->
    <view class="wz_jz xyy pm ba_white" style="width: 100%;left: 0;top: 0;z-index: 1;height: 110px;">
      <view class="ddisp bhh he_max topdq">
<!--        style="width:calc(100% - 51px)"-->
        <view class="czjz_flex" style="width: 100%">
          <up-tabs :list="classShopList" keyName="name" lineColor="#3a9e5f"
                   itemStyle="padding:10px;box-sizing: border-box;"
                   :current="selectedTabIndex"
          >
            <template #content="{item, keyName, index}">
              <view @click="addTopShop(item,index)">
                <view>
                  <image :src="item.image" style="width: 60px;height: 60px" />
                </view>
                <view class="fz_12">
                  {{ item.name }}
                </view>
              </view>
            </template>
          </up-tabs>
        </view>
        <view v-if="false" class="czjz_flex he_max topdq wh_f" style="width: 50px;">
          <view>
            <view style="margin-top: 20px">
              <view>全</view>
              <view>部</view>
              <view class="mag_t-5">
                <img src="../../static/icon/quanbu.png"
                     style="width: 12px;height: 12px"/></view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view style="height: 110px"></view>
<!--    中间商品部分-->
    <view class="wh_f ccgl-y mag_t-10"  style="height: calc(100vh - 120px);">
      <!--      左侧二级菜单-->
      <view class="left_menu fz_14 ccgl-y"
            style="width: 100px;
            height: 100%;
            background-color: #f4f4f4;
            border-radius: 0 20px 0 0">
          <view :class="item.id==classId?'xz_menu':''"
                @click="addMenu(item,index,true)"
                v-for="(item,index) in classTopList" :key="item.id">
            <image class="centerdq mag_l-15" :src="item.imgUrl"
                   style="width: 16px;height: 16px" alt="" />
            <text class="xbt_lx centerdq fz_14" style="line-height: 16px">
              {{ item.id }}
            </text>
          </view>

          <view :class="item.id==classId?'xz_menu':''"
                @click="addMenu(item,index,false)"
                v-for="(item,index) in classList" :key="index">
            <text style="margin-right: 10px" :class="item.id==classId?'xz_lx':''"></text>
            <text class="xbt_lx">{{ item.name }}</text>
          </view>

          <view v-if="list.length>0" style="height: 60px"></view>
        </view>
      <!--    商品列表-->
      <view class="flex_1">
        <scroll-view :scroll-y="true" style="height: calc(100vh - 120px)" class="scrollView"
                     @scrolltolower="scrolltolower()">
          <view class="wh_9 jz lbcss" style="padding-bottom: 10px">
            <view class="em" style="padding: 10px 0 0">{{ className }}</view>
              <view @click="addDetail(item)" class="mag_t-10 wh_f" v-for="(item,index) in listShop" :key="index">
                <view style="width: 80px">
                  <view class="img_zfx">
                    <image class="bor_10" :src="item.image[0]" />
                  </view>
                </view>
                <view class="flex_1 fz_10">
                  <view class="wh_9 jz">
                    <view class="fz_12 em ccsl_2" style="color: #383838">{{ item.name }}</view>
                    <view class="split_2" style="padding: 2px 0">
                      <view>月售 {{ item.sales }}+</view>
                      <view>库存 {{ item.stock }}</view>
                    </view>
                    <view class="fz_10 wz_white">
                      <text class="wz_hui scx">￥ {{ item.re_price }} </text>
                      <text style="border-radius: 3px;padding: 2px 5px;margin-left: 10px;
                    background-color: #d5f0dd;color: #3a9e5f">{{ item.category_pstr }}</text>
                    </view>
                    <view class="split_2" style="padding: 0 0 3px">
                      <view>
                        <view style="color:#e63946;">
                          <text>￥</text>
                          <text class="fz_14 em">{{ parseInt(item.price) }}</text>
                          <text>.{{ String(item.price).split('.')[1] }}</text>
                        </view>
                      </view>
                      <view class="split_3">
                        <view class=" wz_rigdq">
                          <image v-if="item.cart_amount>0" @click.stop="addShopList(false,item,index,$event)" class="centerdq" src="../../static/img/jianshao.png" style="width: 20px;height: 20px"/>
                        </view>
                        <view class="wz_jz centerdq">
                          <text v-if="item.cart_amount>0" class="centerdq">{{ item.cart_amount }}</text>
                        </view>
                        <view>
                          <image @click.stop="addShopList(true,item,index)" class="centerdq" src="../../static/img/tianjia.png" style="width: 18px;height: 18px"/>
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
              <view v-if="listShop.length<1">
                <view class="jz_flex" style="margin-top: 50%">
                  <view class="wz_jz">
                    <image style="width: 150px;height: 90px" src="https://xdjzapi.towngo.cn/uploads/images/wx/202507/08/xcx_1751945016_KEXbwbZngN.png"></image>
                    <view class="mag_t-20 wz_hui">暂无商品 !</view>
                  </view>
                </view>
              </view>
          </view>
          <view v-if="list.length>0" style="height: 60px"></view>
        </scroll-view>
      </view>
    </view>
    <!--    底部结算-->
    <view v-if="list.length>0" class="pm ba_white box_yy" style="width: 100%;height:60px;left: 0;bottom: 0">
      <view class="wh_f he_max">
        <view class="flex_1 wh_f czjz_flex ">
          <view class="wz_jz xd" style="width: 90px">
            <img v-if="list.length<1" src="../../static/img/clz_1.png" style="width: 60px;height: 50px"/>
            <img v-if="list.length>0" src="https://xdjzapi.towngo.cn/uploads/images/wx/202507/03/xcx_1751509991_6PMXlVQxyK.png" style="width: 60px;height: 50px"/>
          </view>
          <view class="flex_1 czjz_flex">
            <view class="wh_max boxs" style="padding-right: 10px">
              <view v-if="list.length>0" class="wh_max wz_rigdq wz_red fz_12">
                <view>
                  <text class="wz_hui bottomdq">已选 {{ list.length }} 件 </text>
                </view>
                <view>
                  <text class="wz_hei fz_14 bottomdq" style="margin: 0 10px">合计:</text>
                  <text class=" bottomdq">￥</text>
                  <text class="fz_16 em bottomdq">{{ parseInt(shopAge.pay_price_no_pei) }}</text>
                  <text v-if="shopAge.pay_price_no_pei!==0" class="em bottomdq">.{{ String(shopAge.pay_price_no_pei).split('.')[1] }}</text>
                </view>
                <view class=" fz_10">
                  共计优惠 <text>{{shopAge.discount_price}}</text>
                </view>
              </view>
<!--              <view v-if="shopList.length>0" class=" fz_12" style="color:#e63946;">-->
<!--                <text class="">￥</text>-->
<!--                <text class="fz_16 em">{{ parseInt(OrderAge) }}</text>-->
<!--                <text class="em">.{{ String(OrderAge).split('.')[1] }}</text>-->
<!--              </view>-->
<!--              <view class="wz_hui fz_10 mag_t-5">免配送费</view>-->
            </view>
          </view>
        </view>
        <view v-if="false" class="flex_1"></view>
        <view class="czjz_flex he_max">
<!--          <view v-if="shopList.length===0" class="jz_flex wz_white bor_25 mag_r-10"-->
<!--                style="background-color: #d5f0dd;width: 110px;height: 40px">-->
<!--            <text style="color: #3a9e5f">￥19.9 起送</text>-->
<!--          </view>-->
          <view @click="submitOrder" class="jz_flex wz_white bor_25 mag_r-10"
                style="background-color: #3a9e5f;width: 110px;height: 40px">
            <text>结算</text>
          </view>
        </view>
      </view>
    </view>
    <up-toast ref="uToastRef"></up-toast>
  </view>
</template>
<script>
import {
  addCartAmount,
  addShoppingCart, delCart,
  getactivityShopList,
  getsaleShopList, getShopCartCount,
  getShopClassList,
  getShopGoodsList,
  gettwoShopList, settlementDetail, shoppingCartList
} from "../../Api/shop";

export default {
  data() {
    return {
      isAddressShow:true,
      title: 'Hello',
      psfs:[{id:1,title:"统一外送"},{id:2,title:"到站自提"},{id:3,title:"送货上门"}],
      psfs_id:1, //默认取货方式
      shopList:[], //购物车列表
      listShop:[], //商品列表
      classList:[],
      classShopList:[], //一级菜单列表
      classTopList:[
        { id:"买过",imgUrl:'../../static/icon/mg.png',lable:'买过', value:111, isTrue:false },
        { id:"推荐",imgUrl:'../../static/icon/tj.png',lable:'推荐', value:222, isTrue:false },
        { id:"活动",imgUrl:'../../static/icon/hd.png',lable:'活动', value:333, isTrue:false },
        { id:"限时",imgUrl:'../../static/icon/xs.png',lable:'限时盒马兑换卡', value:444, isTrue:false },
      ],
      //左侧导航菜单列表
      classId:null, //选中的菜单id
      className:"", //选中的菜单名称
      tjbd:[
        {
          id:1,
          name:'泥螺',
          age:69,
          imgUrl:'../../static/img/nl.png',
        },
        {
          id:2,
          name:'海蜇',
          age:69,
          imgUrl:'../../static/img/hz.png',
        },
        {
          id:1,
          name:'Kj大骨头',
          age:69,
          imgUrl:'../../static/img/kj.png',
        },
      ], //推荐榜单
      OrderAge:'0.00',
      page:1,
      pageSize:10,
      shopNum:0,
      shopAge:{},
      selectedTabIndex: 0,    // 当前选中的 tab 索引
      list:[], //购物车列表
      actItem:{},
      jzisTrue:1
    }
  },
  methods: {
    getShopCartCount(){
      getShopCartCount().then(res => {
        if(res.data.count>0){
          uni.setTabBarBadge({
            index: 2,
            text: String(res.data.count)
          })
        }else{
          uni.removeTabBarBadge({
            index:2
          })
        }
      })
    },
    addDetail(e){
      const params = { id:e.id}; // 待传递的参数
      uni.navigateTo({
        url: `/shophome/shopDetail/index?id=${params.id}`
      });
    },
    scrolltolower(){
      if(this.className == '买过' || this.className == '推荐' || this.className == '活动'){
        // 如果 jzisTrue = 3 没有更多数据了
        if(this.jzisTrue == 1){
          if(this.page === 1){
            this.page += 1
          }
          this.jzisTrue = 2
          // 触底了
          setTimeout(()=>{
            this.jzisTrue = 1
            this.actFy(this.actItem,1,true)
          },1000)
        }
      }else{
        // 如果 jzisTrue = 3 没有更多数据了
        if(this.jzisTrue === 3){

        }else{
          if(this.page === 1){
            this.page += 1
          }
          this.jzisTrue = 2
          // 触底了
          setTimeout(()=>{
            this.jzisTrue = 1
            this.getShopList()
          },1000)
        }
      }
    },
    // 二级菜单商品
    getShopList(e){
      getShopGoodsList({
        category_id:this.classId,
        page:this.page
      }).then(res=>{
        // 如果没有数据 说明已经没有更多数据了 改变底部加载状态为3
        if(res.data.data.length<1){
          this.jzisTrue = 3
        }else{
          this.page += 1
          //有数据 正常合并新的数据
          this.listShop = this.listShop.concat(res.data.data); // 或者使用:
        }
        // this.listShop.push(res.data.data)
        this.listShop.forEach(item => {
          item.sum = 0; // 添加 sum 字段并赋值为 0
        });
        // console.log('二级菜单商品',this.listShop)
      })
    },

    // 点击一级分类
    addTopShop_old(e){
      this.selectedTabIndex = index;  // 更新选中的 tab 索引
      gettwoShopList(e.id).then(res=>{
        this.classList = res.data
        if(res.data.length>0){
          this.addMenu(this.classList[0],0,false)
        }else{
          this.classList = []
          this.listShop = []
        }
      })
    },
    // 结算
    submitOrder(){
      uni.switchTab({
        url: '/pages/shoppingCart/index'
      });
    },
    //消息提示
    showToast(msg, type = "default") {
      uni.showToast({
        title: msg,
        icon: "none", // 图标类型，可选值：success, none
        duration: 2000 // 显示时间，单位毫秒
      });
    },
    countShop(){
      shoppingCartList().then((res)=>{
        this.list = res.data
        if(res.data.length>0){
          settlementDetail({
            act_id:0,
            data: res.data
          }).then(res=>{
            this.shopAge = res.data
          })
        }
      })
    },
    //添加商品或减少商品数量
    addShopList(t,item,index,data){
      // 添加
      if(t){
        // 下单数量小于库存
        if(this.listShop[index].cart_amount<item.stock){
          addShoppingCart({
            goods_id:item.id
          }).then(res=>{
            this.listShop[index].cart_amount += 1
            this.shopNum += 1
            this.countShop()
            this.getShopCartCount()
          }).catch(err=>{
            console.log('失败了')
          })
          // 已存在改变它的数量 不添加数据
          // if(shop){
          //   this.shopList[index].sum += 1
          // }else{
          //   this.shopList.push({
          //     id:item.id,
          //     name:item.name,
          //     price:item.price,
          //     sum:item.sum
          //   })
          // }
          // this.shopNum += 1
        }else{
          this.showToast('库存不足')
        }
        // 减少
      }else{
        delCart({
          goods_id:item.id,
          amount:1
        }).then(res=>{
          this.listShop[index].cart_amount -= 1
          this.getShopCartCount()
          this.countShop()
        })
        // 减少数量需要大于0
        // if(this.listShop[index].sum>0){
        //   delCart({
        //     goods_id:item.id
        //   }).then(res=>{
        //     this.listShop[index].sum -= 1
        //     this.shopNum -= 1
        //     console.log('删除结果',res)
        //   })
        //   this.shopNum -= 1
        // }
      }
    },
    //添加商品或减少商品数量
    addShopList_2(t,item,index){
      // 添加
      if(t){
        this.listShop[index].sum += 1
        // 下单数量小于库存
        if(this.listShop[index].sum<item.stock){
          // 查询此次添加的商品是否已存在
          let shop = this.shopList.find(items=>items.id == item.id)
          // 已存在改变它的数量 不添加数据
          if(shop){
            this.shopList[index].sum += 1
          }else{
            this.shopList.push({
              id:item.id,
              name:item.name,
              price:item.price,
              sum:item.sum
            })
          }
          this.shopNum += 1
        }
        // 减少
      }else{
        // 减少数量需要大于0
        if(this.listShop[index].sum>0){
          this.listShop[index].sum -= 1
          if(this.shopList[index].sum>1){
            // console.log('删除数量',this.shopList)
            this.shopList[index].sum -= 1
          }else{
            this.shopList[index].sum -= 1
            this.shopList.splice(index, 1);
            // console.log('删除商品',this.shopList)
          }
          this.shopNum -= 1
        }
      }
    },
    //添加商品或减少商品数量
    addShopList_Old(t,item,index){
      // 添加
      if(t){
        this.listShop[index].sum += 1
        // 下单数量小于库存
        if(this.listShop[index].sum<item.stock){
          // 查询此次添加的商品是否已存在
          let shop = this.shopList.find(items=>items.id == item.id)
          // 已存在改变它的数量 不添加数据
          if(shop){
            this.shopList[index].sum += 1
          }else{
            this.shopList.push({
              id:item.id,
              name:item.name,
              price:item.price,
              sum:item.sum
            })
          }
        }
        // 减少
      }else{
        // 减少数量需要大于0
        if(this.listShop[index].sum>0){
          this.listShop[index].sum -= 1
          if(this.shopList[index].sum>1){
            // console.log('删除数量',this.shopList)
            this.shopList[index].sum -= 1
          }else{
            this.shopList[index].sum -= 1
            this.shopList.splice(index, 1);
            // console.log('删除商品',this.shopList)
          }
        }
      }
    },
    //点击二级菜单
    addMenu(e,i,t){
      this.page = 1
      this.jzisTrue = 1
      if(t){
        this.actItem = e
        switch (e.id){
          case "买过":
            getsaleShopList().then(res=>{
              this.listShop = res.data.data
            })
            break;
          case "推荐":
            getShopGoodsList({
              hots_type:1
            }).then(res=>{
              this.listShop = res.data.data
            })
            break;
          case "活动":
            getactivityShopList().then(res=>{
              this.listShop = res.data.data
            })
            break;
          case "限时":
            getShopGoodsList({category_id:456}).then(res=>{
              this.listShop = res.data.data.filter(item=>{
                if(item.name.includes('盒马')){
                  return item
                }
              })
            })
            break;
        }
      }else{
        uni.setStorageSync('class_shop_id',{id:e.id})
        getShopGoodsList({
          category_id:e.id
        }).then(res=>{
          this.listShop = res.data.data
          this.listShop.forEach(item => {
            item.sum = 0; // 添加 sum 字段并赋值为 0
          });
        })
      }
      this.classId = e.id
      this.className = e.lable
    },
    actFy(e){
      switch (e.id){
        case "买过":
          getsaleShopList({
            page:this.page
          }).then(res=>{
            // 如果没有数据 说明已经没有更多数据了 改变底部加载状态为3
            if(res.data.data.length<1){
              this.jzisTrue = 3
            }else{
              this.page += 1
              //有数据 正常合并新的数据
              this.listShop = this.listShop.concat(res.data.data); // 或者使用:
            }
          })
          break;
        case "推荐":
          getShopGoodsList({
            hots_type:1,
            page:this.page
          }).then(res=>{
            // 如果没有数据 说明已经没有更多数据了 改变底部加载状态为3
            if(res.data.data.length<1){
              this.jzisTrue = 3
            }else{
              this.page += 1
              //有数据 正常合并新的数据
              this.listShop = this.listShop.concat(res.data.data); // 或者使用:
            }
          })
          break;
        case "活动":
          getactivityShopList({
            page:this.page
          }).then(res=>{
            // 如果没有数据 说明已经没有更多数据了 改变底部加载状态为3
            if(res.data.data.length<1){
              this.jzisTrue = 3
            }else{
              this.page += 1
              //有数据 正常合并新的数据
              this.listShop = this.listShop.concat(res.data.data); // 或者使用:
            }
          })
          break;
        case "限时":
          getShopGoodsList({category_id:456}).then(res=>{
            this.listShop = res.data.data.filter(item=>{
              if(item.name.includes('盒马')){
                return item
              }
            })
          })
          break;
      }
    },
    addShop(e){
      this.shopList.push({
        id:e.id,
        name:e.name,
        age:e.age
      })
    },
    addPsfs(e){
      this.psfs_id = e
    },

    //从首页来查询二级菜单
    getIndexList(class_id){
      gettwoShopList(class_id).then(res=>{
        this.classList = res.data
        if(res.data.length>0){
          this.addMenu(this.classList[0],0,false)
        }else{
          this.classList = []
          this.listShop = []
        }
      })
    },

    addTopShop(item, index) {
      this.jzisTrue = 1
      uni.setStorageSync('classTabs',{list:item})
      this.selectedTabIndex = index;  // 更新选中的 tab 索引
      gettwoShopList(item.id).then(res => {
        this.classList = res.data;
        if (res.data.length > 0) {
          // 选中第一个二级菜单项
          let two_id = uni.getStorageSync('class_shop_id')
          const index = this.classList.findIndex(item => item.id == two_id.id);
          if(index && index!='-1'){
            this.addMenu(this.classList[index], 0, false);
          }else{
            this.addMenu(this.classList[0], 0, false);
          }
        } else {
          this.classList = [];
          this.listShop = [];
        }
      });
    },
  },
  onShow() {
    this.className = ""
    this.classId = ""
    //获取一级分类
    gettwoShopList().then(res=>{
      this.classShopList = res.data
      if(res.data.length>0){
          // 判断是不是从首页跳过来的 需要模拟点击二级菜单获取数据
          let classTabs_id = uni.getStorageSync('classTabs');
          if(classTabs_id){
            // 手误修正，这里取得了 classTabs_id 然后找到其在 classShopList 中的索引
            const index = this.classShopList.findIndex(item => item.id === classTabs_id.list.id);
            setTimeout(()=>{
                this.selectedTabIndex = index; // 更新选中索引
                this.addTopShop(classTabs_id.list, index); // 调用查询
            },500)
          }else{
            this.selectedTabIndex = 0
            gettwoShopList(res.data[0].id).then(res=>{
              this.classList = res.data
              if(res.data.length>0){
                this.addMenu(this.classList[0],0,false)
              }else{
                this.classList = []
                this.listShop = []
              }
            })
          }
      }
    })

    const token = uni.getStorageSync('userToken');
    if(token){
      this.countShop()
    }
  },
  watch:{
    shopList: {
      handler(newVal, oldVal) {
        // 当 shopList 发生变化时执行
        let money = this.shopList.reduce((total, item) => {
          // 将 money 转换为数字并计算
          let price = parseFloat(item.price) || 0; // 确保是数字，若无法转换则为 0
          const quantity = item.sum || 0; // 使用数量
          return total + price * quantity; // 累加总价
        }, 0); // 初始值为 0
        if(money == '0'){
          this.OrderAge = String('0.00')
        }else{
          this.OrderAge = String(money)
        }
        console.log('购物车发生变化:', this.shopList)
        // 你可以在这里执行其他逻辑，比如更新其他数据
      },
      deep: true // 如果 shopList 是一个对象数组，可以使用 deep: true 进行深度监听
    }
  },
  mounted() {
    uni.$on('ref',(data)=>{
      console.log("传递了",data)
    })
  },
  onShareAppMessage() {
    return{
      title:'鲜到家族云享集市',
      path:'/pages/index/index'
    }
  },
  //2.配置分享到朋友圈
  onShareTimeline(){
    return{
      title: '鲜到家族云享集市',                //分享的标题
      query: '/pages/index/index',     //点击分享链接之后进入的页面路径
      imageUrl: '/static/img/logo.jpg' //分享发送的链接图片地址
    }
  }
}
</script>

<style lang="scss">
.tabs{
  ::v-deep.u-tabs__wrapper__nav__line{
    transform: translate(25px)!important;
  }
}
.lbcss{
  ::v-deep .u-line{
    border: none!important;
  }
}
.xz_lx{
  height: 30px;
  width: 6px;
  background-color: #3a9e5f;
  border-radius: 0 10px 10px 0;
}
.xz_menu{
  background-color: white;
}
.xbt_lx{
  margin-left: 10px;
}
.left_menu>view{
  height: 50px;
  display: flex;
  align-items: center;
}
.psfs_xz{
  background-color: #3a9e5f;
  color: white;
}
.psfs{
  color: #3a9e5f;
}
.sy_bg{
  background-image: url("https://xdjzapi.towngo.cn/wx/indextopbj.png");
  background-size: 100% 100%;
}
</style>
